package com.kime.email.javamail;

import javax.mail.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 接收邮件
 */
public class ReceiveEmail {

    // 发件人昵称
    private static String userName;
    // 发件人密码/授权码
    private static String password;

    /**
     * 通过加载器初始加载 receiveEmailInfo.properties 文件，获取属性值
     */
    static {
        try {
            InputStream resource = ClassLoader.getSystemResourceAsStream("receiveEmailInfo.properties");
            Properties properties = new Properties();
            properties.load(resource);
            userName = properties.getProperty("email.userName");
            password = properties.getProperty("email.password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收邮件
     */
    public void receiveEmail() {
        // 获取属性
        Properties properties = new Properties();
        // 使用的协议
        properties.setProperty("mail.transport.protocol", "pop3");
        // 服务器地址
        properties.setProperty("mail.smtp.host", "pop.163.com");
        // 获取连接
        Session session = Session.getDefaultInstance(properties);
        try {
            // 获取 store 对象
            Store store = session.getStore("pop3");
            // pop3 服务器登陆认证
            store.connect("pop.163.com", userName, password);
            // 获得用户的邮件帐户
            Folder folder = store.getFolder("INBOX");
            // 设置对邮件帐户的访问权限
            folder.open(Folder.READ_WRITE);
            // 得到邮箱帐户中的所有邮件
            Message[] messages = folder.getMessages();
            for (Message message : messages) {
                // 获得邮件主题
                String subject = message.getSubject();
                // 获得发送者地址
                Address address = (Address) message.getFrom()[0];
                System.out.println("邮件的主题为: " + subject + "\t发件人地址为: " + address);
                System.out.println("邮件的内容为：");
                // 输出邮件内容到控制台
                message.writeTo(System.out);
            }
            // 关闭邮件账户对象
            folder.close(false);
            // 关闭连接对象
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ReceiveEmail receiveEmail = new ReceiveEmail();
        receiveEmail.receiveEmail();
    }
}
